<template>
  <NCard class="login-card" title="登录">
    <NForm :model="loginModel">
      <NFormItem path="username" label="用户名">
        <NInput
          v-model:value="loginModel.username"
          placeholder="请输入用户名"
          @keydown.enter.prevent="submit"
        />
      </NFormItem>
      <NFormItem path="password" label="密码">
        <NInput
          v-model:value="loginModel.password"
          type="password"
          @keydown.enter.prevent="submit"
          placeholder="请输入密码"
        />
      </NFormItem>
      <div class="login-button">
        <NButton @click="submit" type="primary">登录</NButton>
        <NButton @click="toRegister" type="primary" strong secondary
          >去注册</NButton
        >
      </div>
    </NForm>
  </NCard>
</template>

<script lang="ts" setup>
import { NCard, NForm, NFormItem, NInput, NButton, useMessage } from "naive-ui";
import { useRouter } from "vue-router";

import { useLogin } from "@/hooks/Login";

const router = useRouter();
const message = useMessage();
const { loginModel, toLogin } = useLogin();

async function submit() {
  try {
    const msg = await toLogin();
    router.push("/");
    message.success(msg);
  } catch (e: any) {
    message.error(e.response.data.msg);
  }
}

function toRegister() {
  router.push("/register");
}
</script>

<style lang="less" scoped>
.login-card {
  max-width: 500px;
  margin: 3em auto;
  padding: 2em 1em;

  .login-button {
    margin: 1em 0;
    display: flex;
    justify-content: space-around;

    button {
      padding: 0.5em 3em;
    }
  }
}
</style>
